# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def detectCycle(self, head) :
        if not head or head.next == None:
            return None
        i = head
        j = head
        # pos_i = 0
        # pos_j = 0

        while True:
            if i != None and j != None:
                i = i.next
                j = j.next
                # pos_i = pos_i+1
                # pos_j = pos_j+1
                if i!=None and j != None:
                    j = j.next
                    # pos_j= pos_j+1
                    if i == j :

                        while head!=i:
                            head = head.next
                            i = i.next
                        return head
                else:
                    return None
            else:
                return None




if __name__ == '__main__':
    one = ListNode(3)
    two = ListNode(2)
    three = ListNode(0)
    four = ListNode(-4)
    one.next = two
    two.next = three
    three.next = four
    four.next = two

    # one = ListNode(1)
    # two = ListNode(2)
    # one.next = two
    # two.next = one
    S = Solution()
    T = S.detectCycle(one)
    print(T.val)
